// 定义主题颜色
const THEME = {
    PRIMARY: "#CC3333",        // 主红色
    SECONDARY: "#FF6666",      // 浅红色
    BACKGROUND: "#FFF0F0",     // 浅红背景色
    TEXT_PRIMARY: "#CC3333",   // 文字红色
};

let loginView = ui.inflate(
    <vertical bg={THEME.BACKGROUND}>
        <appbar bg={THEME.PRIMARY}>
            <toolbar id="toolbar" title="tomato" titleTextColor="#ffffff"/>
        </appbar>
        
        <card w="*" h="auto" margin="20 50 20 0" cardCornerRadius="10dp" 
              cardElevation="3dp" foreground="?selectableItemBackground">
            <vertical padding="20">
                <text text="账号登录" textColor={THEME.TEXT_PRIMARY} textSize="24sp" 
                      gravity="center" margin="0 0 0 20" textStyle="bold"/>
                
                <input id="username" hint="请输入账号" textSize="16sp" margin="0 40 0 0"/>
                <input id="password" hint="请输入密码" textSize="16sp" margin="0 20 0 0" password="true"/>

                <card w="*" h="45" margin="0 20 0 10" cardCornerRadius="5dp"
                      cardBackgroundColor={THEME.PRIMARY} cardElevation="0dp">
                    <button id="loginBtn" text="登录" textColor="#ffffff" textSize="16sp"
                            style="Widget.AppCompat.Button.Borderless" w="*" h="*"/>
                </card>

                <card w="*" h="45" margin="0 10 0 10" cardCornerRadius="5dp"
                      cardBackgroundColor="#666666" cardElevation="0dp">
                    <button id="exitBtn" text="退出" textColor="#ffffff" textSize="16sp"
                            style="Widget.AppCompat.Button.Borderless" w="*" h="*"/>
                </card>

                <text id="version" text="版本号：1.0.1" textSize="12sp" 
                      textColor="#666666" gravity="center" margin="0 20"/>
            </vertical>
        </card>
    </vertical>
);

let loginStorage = storages.create("login_info");

// 保持原有的功能代码不变
function initLoginPage(callback) {
    loginView.loginBtn.click(function() {
        let username = loginView.username.text();
        let password = loginView.password.text();
        
        if (!username || !password) {
            toast("请输入账号和密码");
            return;
        }

        // 在UI线程中创建并显示加载对话框
        let loading = dialogs.build({
            title: "登录中",
            content: "请稍候...",
            cancelable: false
        }).show();

        // 创建超时标记
        let isTimeout = false;
        let isCompleted = false;

        // 设置超时处理
        let timeoutId = setTimeout(function() {
            if (!isCompleted) {
                isTimeout = true;
                ui.run(function() {
                    try {
                        if (loading && loading.isShowing()) {
                            loading.dismiss();
                        }
                        toast("登录请求超时，请检查网络后重试");
                    } catch (e) {
                        console.error("超时处理异常：" + e);
                    }
                });
            }
        }, 15000);

        // 在子线程中执行网络请求
        threads.start(function() {
            if (isTimeout) return; // 如果已超时，不执行后续操作
            
            try {
                // 准备请求参数
                let url = "http://106.53.210.53:3030/login";
                let params = {
                    login_name: username,
                    password: password
                };
                
                // 执行网络请求
                let response = http.post(url, params);
                
                // 标记请求完成
                isCompleted = true;
                
                // 处理响应结果
                let resultSuccess = false;
                let resultData = null;
                let resultMessage = "";
                
                try {
                    // 解析JSON响应
                    let jsonStr = response.body.string();
                    let result = JSON.parse(jsonStr);
                    
                    if (result.code === 1) {
                        resultSuccess = true;
                        resultData = result.data;
                        resultMessage = result.msg || "登录成功";
                    } else {
                        resultMessage = result.message || result.msg || "登录失败";
                    }
                } catch (parseError) {
                    resultMessage = "数据解析错误：" + parseError;
                }
                
                // 在UI线程中更新界面
                ui.run(function() {
                    try {
                        // 清除超时计时器
                        clearTimeout(timeoutId);
                        
                        // 关闭加载对话框
                        if (loading && loading.isShowing()) {
                            loading.dismiss();
                        }
                        
                        if (resultSuccess) {
                            // 存储登录信息和权限
                            loginStorage.put("isLoggedIn", true);
                            loginStorage.put("username", username);
                            if (resultData && resultData.permissions) {
                                loginStorage.put("permissions", resultData.permissions);
                            }
                            
                            // 回调通知
                            if (callback) {
                                callback(true, resultData);
                            }
                            
                            toast("登录成功");
                        } else {
                            toast(resultMessage);
                        }
                    } catch (uiError) {
                        console.error("UI更新异常：" + uiError);
                    }
                });
            } catch (networkError) {
                // 标记请求完成
                isCompleted = true;
                
                // 在UI线程中处理网络错误
                ui.run(function() {
                    try {
                        // 清除超时计时器
                        clearTimeout(timeoutId);
                        
                        // 关闭加载对话框
                        if (loading && loading.isShowing()) {
                            loading.dismiss();
                        }
                        
                        toast("网络请求失败：" + networkError);
                    } catch (e) {
                        console.error("错误处理异常：" + e);
                    }
                });
            }
        });
    });
    
    // 添加退出按钮点击事件
    loginView.exitBtn.click(function() {
        // 退出应用
        exit();
    });
}
// 权限检查函数
function hasPermission(permission) {
    let permissions = loginStorage.get("permissions", []);
    return permissions.includes(permission);
}

// 检查用户类型
function getUserType() {
    return loginStorage.get("user_type", "user");
}

// 检查token是否过期
function isTokenExpired() {
    let expireTime = loginStorage.get("expire_time", 0);
    return Date.now() > expireTime;
}


// 保持原有的其他函数不变
function checkLoginFromServer(username, password, callback) {
    setTimeout(function() {
        let success = (username === "admin" && password === "123456");
        callback(success);
    }, 1000);
}

function checkLoginStatus() {
    return loginStorage.get("isLoggedIn", false);
}

function logout() {
    loginStorage.clear();
}

module.exports = {
    loginView: loginView,
    initLoginPage: initLoginPage,
    checkLoginStatus: checkLoginStatus,
    logout: logout
};